'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 铁匠铺
 * @author sundbcn@gmail.com (sun debing)
 */

var mongoose = require('mongoose');
var _ = require('lodash');
var dataApi = require('../../libs/dataApi');
var smithyScheduleSchema = require('./smithyScheduleSchema.js');
var moment = require('moment');
var smithyMgr = require('../../mgr/smithyMgr.js');
var constantUtil = require('../../util/constantUtil.js');

/**
 * 初始化精力
 * @return {[type]} [description]
 */
var _initEnergy = function () {
    return constantUtil.value('energy_max_limit');
};
///////////////////////////////////////////////////////////
/**
 * 铁匠铺
 * @type {mongoose}
 */
var smithySchema = new mongoose.Schema({
    // 角色id
    role_id: {
        type: Number,
        required: true,
        unique: true,
        index: true
    },

    // 铁匠铺ID 默认开启一个工匠
    open_smithy_list: {
        type: [Number],
        default: [1]
    },

    // 工人开放列表
    open_worker_list: {
        type: [Number]
    },

    // 精力
    energy: {
        type: Number,
        default: _initEnergy
    },

    // 最大精力
    max_energy: {
        type: Number,
        default: _initEnergy
    },

    // 精力购买次数
    energy_times: {
        type: Number,
        default: 0
    },

    // 上次回复体力时间
    last_recover_time: {
        type: Date,
        default: Date.now
    },

    // 队列
    worker_list: [smithyScheduleSchema]
});

smithySchema.pre('save', function (next) {
    this.increment();
    if (!this.isNew && !!this.isModified()) {
        this.pushModify();
    }
    next();
});

/**
 * 设置队列时间
 */
smithySchema.methods.setWorkerTime = function (smithy_id, time) {
    var now_time = moment();
    _.some(this.worker_list, function (item) {
        if (item.smithy_id == smithy_id) {
            if (item.end_time > now_time) {
                item.end_time = moment(item.end_time).add(-time, 's');
            }
            return true;
        }
    });
};

/**
 * 增加精力购买次数
 */
smithySchema.methods.addEnergyNum = function () {
    this.energy_times++;
};

/**
 * 获取精力购买次数
 */
smithySchema.methods.getEnergyNum = function () {
    return this.energy_times;
};

/**
 * 获取精力
 */
smithySchema.methods.getEnergy = function () {
    return this.energy;
};

/**
 * 扣除精力
 */
smithySchema.methods.subEnergy = function (sub_energy) {
    sub_energy = parseInt(sub_energy);
    if (this.energy < sub_energy) {
        return false;
    }
    var full_energy = (this.energy >= this.max_energy);
    this.energy -= sub_energy;
    if (full_energy && this.energy < this.max_energy) {
        this.last_recover_time = moment();
    }

    return true;
};

/**
 * 设置体力回复的时间
 */
smithySchema.methods.resetEnergyRecoverTime = function () {
    return this.last_recover_time = moment();
};

/**
 * 获取体力回复时间
 */
smithySchema.methods.getEnergyRecoverTime = function () {
    return this.last_recover_time;
};

/**
 * 增加精力
 */
smithySchema.methods.addEnergy = function (value) {
    value = parseInt(value);
    this.energy += value;
};

/**
 * 开启工匠槽
 */
smithySchema.methods.openSmithy = function (smithy_id) {
    if (!!this.isSmithyOpenOK(smithy_id)) {
        this.open_smithy_list.push(smithy_id);
    }
};

/**
 * 开启工人列
 */
smithySchema.methods.openWorker = function (worker_id) {
    if (!!this.isWorkerOpenOK(worker_id)) {
        this.open_worker_list.push(worker_id);
    }
};

/**
 * 获取工匠槽列表
 */
smithySchema.methods.getSmithyOpenList = function () {
    return this.open_smithy_list;
};

/**
 * 获取工人列表
 */
smithySchema.methods.getWorkerOpenList = function () {
    return this.open_worker_list;
};

/**
 * 获取排程列表
 */
smithySchema.methods.getWorkerSchedule = function () {
    return this.worker_list;
};

/**
 * 开启的工匠槽是否为当前工匠的下一级
 */
smithySchema.methods.isSmithyOpenOkNext = function (smithy_id) {
    var last_item = parseInt(_.last(this.getSmithyOpenList()));
    if (last_item + 1 == +smithy_id) {
        return true;
    }
    return false;
};

/**
 * 工人是否开放
 */
smithySchema.methods.isWorkerOpenOK = function (worker_id) {
    return _.indexOf(this.getWorkerOpenList(), worker_id) == -1;
};

/**
 * 工匠槽是否开放
 */
smithySchema.methods.isSmithyOpenOK = function (smithy_id) {
    return _.indexOf(this.getSmithyOpenList(), smithy_id) == -1;
};

/**
 * 获取队列是否存在
 * @return {[type]} [description]
 */
smithySchema.methods.isWorkerSchedule = function (smithy_id) {
    var worker_list = this.getWorkerSchedule();

    for (var i = 0; i < worker_list.length; i++) {
        var item = worker_list[i];

        if (item.smithy_id == smithy_id) {
            return {
                item: item,
                state: true
            };
        }
    }
    return false;
};

/**
 * 是否还有队列可精练
 */
smithySchema.methods.isOk = function () {
    if (_.size(this.getSmithyOpenList()) <= _.size(this.getWorkerSchedule())) {
        return false;
    } else {
        return true;
    }
};

/**
 * 添加排程
 */
smithySchema.methods.addWorkerSchedule = function (smithy_id, worker_id, need_time, production_time) {

    // 是否还有精练队列
    if (_.size(this.getSmithyOpenList()) <= _.size(this.getWorkerSchedule())) {
        return false;
    }

    // 工人是否开放
    if (!!this.isWorkerOpenOK(worker_id)) {
        return false;
    }

    // 精练队列是否已存在
    if (!!this.isWorkerSchedule(smithy_id)) {
        return false;
    }

    var end_time = moment().add(need_time, 's');
    this.worker_list.push({
        smithy_id: smithy_id,
        worker_id: worker_id,
        total_time: production_time,
        end_time: end_time
    });
    return true;
};

/**
 * 移除排程
 * @return {[type]} [description]
 */
smithySchema.methods.remove = function (worker_id) {
    var remove_item = this.isWorkerSchedule(worker_id);
    if (!remove_item.item) {
        return false;
    }
    remove_item.item.remove();
    return true;
};

/**
 * 获取修改
 * @return {[type]} [description]
 */
smithySchema.methods.getLastChange = function () {
    return this.toJSON();
};

/**
 * 推送给用户
 * @return {[type]} [description]
 */
smithySchema.methods.push = function () {
    this.pushModify();
};

smithySchema.methods.pushModify = function () {
    smithyMgr.sendSmithyChanged(
        this.role_id,
        this.getLastChange(),
        function (err, fails) {
            if (err) {
                console.error('send vip message error: %j, fail ids: %j', err, fails);
                return;
            }
        }
    );
};

if (!smithySchema.options.toJSON) {
    smithySchema.options.toJSON = {};
}

/* jshint unused:false */
smithySchema.options.toJSON.transform = function (doc, ret) {
    delete ret._id;
};
mongoose.model('Smithy', smithySchema);
